package name.fordj.glutil.index;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Indexer<T> {
    private Map<String, Index<T>> idToIndexMap = new HashMap<String, Index<T>>();
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public Index<T> getOrCreateIfNotExist(String id) {
        try {
            readWriteLock.readLock().lock();
            Index<T> index = idToIndexMap.get(id);
            if(index == null) {
                index = new Index<T>(id);
                try {
                    readWriteLock.readLock().unlock();
                    readWriteLock.writeLock().lock();
                    idToIndexMap.put(id, index);
                } finally {
                    readWriteLock.readLock().lock();
                    readWriteLock.writeLock().unlock();
                }
            }
            return index;
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public Index<T> get(String id) {
        try {
            readWriteLock.readLock().lock();
            return idToIndexMap.get(id);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
